const express = require('express')
const router = express.Router()
const path = require('path')
const fs = require('fs')
const multer = require('multer')

const uploadDir = path.join(__dirname, '../uploads')
if(!fs.existsSync(uploadDir)){
    fs.mkdirSync(uploadDir, {recursive:true})
}
console.log('上传目录路径:', uploadDir) // 打印实际路径
console.log('目录是否存在:', fs.existsSync(uploadDir))

const storage = multer.diskStorage({
    destination:(req,file,cb) => {
        cb(null,uploadDir)
    },
    filename:(req,file,cb) => {
        const uniqueSuffix = Date.now() + '-' + Math.round(Math.random() * 1E9)
        cb(null,file.fieldname + '-' + uniqueSuffix +path.extname(file.originalname))
    }
})

const upload = multer({
    storage:storage,
    limits: {
        fileSize: 50 * 1024 * 1024
    }
})

const uploadHandler = (req,res) => {
    if (!req.file) {
        return res.status(400).send({ status: 1, message: '没有文件' })
    }
    console.log('upload事件触发了',req.file);
    
    const fileUrl = `http://localhost:9000/uploads/${req.file.filename}`
    console.log(fileUrl);
    
    res.send({
        status: 0,
        message: '上传成功',
        data: {
            filename: req.file.originalname,
            url: fileUrl,
            size: req.file.size
        }
    })
}

router.post('/upload', upload.single('file'),uploadHandler)

module.exports = router